<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle">
    <BasicForm @register="registerForm" :style="getBoxWidth" class="!mx-auto" />

    <!-- showFooter -->

    <template #footer>
      <Spin :spinning="loading" :delay="200">
        <ButtonActions
          v-if="!isCustom && buttons.length"
          @save="handleSubmit"
          @cancel="handleClose"
          @custom="handleBtnCustom"
          :data="buttons"
        />
        <div v-else>
          <a-button @click="handleSubmit" type="primary">保存</a-button>
          <a-button @click="handleClose">取消</a-button>
        </div>
      </Spin>
    </template>
    <ModelDesign :classify="2" :modelId="dataModelId" @success="init" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { Spin } from 'ant-design-vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import ModelDesign from './ShowModelDesign.vue';

  import ButtonActions from './ButtonActions.vue';
  import { customFnForApi } from '../hooks/functionSet';
  import { isObject } from '/@/utils/is';
  import { toJson, getCSSValue } from '/@/utils';
  import { UseModalInit } from '../hooks/useComFormModel';
  import { useMessage } from '/@/hooks/web/useMessage';

  export default defineComponent({
    name: 'MenuDrawer',
    components: {
      Spin,
      BasicDrawer,
      BasicForm,
      ModelDesign,
      ButtonActions,
    },
    props: {
      isCustom: {
        type: Boolean,
        default: false,
      },
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const loading = ref(false);
      const isUpdate = ref(false);
      const buttons = ref<any>([]);
      const dataModelId = ref('');
      const modalInit = ref<Indexable>({});
      const { createMessage } = useMessage();
      const [registerForm, formActionType] = useForm({
        baseColProps: { span: 23 },
        showActionButtonGroup: false,
      });
      const { resetFields, setProps: setFormProps } = formActionType;

      let rawData: Recordable = {};
      const title = ref('');
      let formWidth = ref('');

      const [registerDrawer, modalFn] = useDrawerInner(async (data) => {
        try {
          rawData = data;
          modalFn.changeLoading(true);
          await init();
        } catch (e) {
          throw e;
        } finally {
          modalFn.changeLoading(false);
        }
      });
      const { setDrawerProps, closeDrawer, changeLoading } = modalFn;
      const params = ref<Indexable>({});
      async function init() {
        const data = rawData;
        resetFields();

        setDrawerProps({ confirmLoading: true });
        isUpdate.value = !!data?.isUpdate;
        dataModelId.value = data.dataModelId;

        // 外层传递进入的窗口参数
        const { complexParams = {} } = data._comParams || {};
        const dataParams = isObject(data.params) ? data.params : toJson(data.params);
        params.value = data.params = {
          ...dataParams,
          ...(complexParams.windowQuery || {}),
          ...(complexParams.windowParam || {}),
          ...(rawData.record || {}),
        };
        modalInit.value = new UseModalInit({ btnData: data as any }, formActionType);
        const {
          btns = [],
          title: name,
          padding,
          width,
          value,
        } = await modalInit.value.initialize();

        title.value = name || '';
        formWidth.value = width || '';
        buttons.value = btns.map((el) => Object.assign(el, data.params, value));
        setDrawerProps({ confirmLoading: false });
        setFormProps({
          baseRowStyle: { padding },
        });
      }

      const getTitle = computed(() => title.value || '');
      const getBoxWidth = computed(() => ({ width: getCSSValue(unref(formWidth), '100%') }));

      async function handleSubmit() {
        try {
          loading.value = true;
          changeLoading(true);
          setDrawerProps({ confirmLoading: true });
          const [ret] = await modalInit.value.useModalSumbit();
          handleClose();
          emit('success', ret, rawData);
          createMessage.success('操作成功', 1.5);
        } finally {
          loading.value = false;
          changeLoading(false);
          setDrawerProps({ confirmLoading: false });
        }
      }

      async function handleClose() {
        closeDrawer();
      }
      async function handleBtnCustom(btnConfig) {
        btnConfig.isForm = true;
        btnConfig.params = params.value;

        customFnForApi(btnConfig, {
          ...formActionType,
          //  弹框方法
          modalFn,
        });
      }
      return {
        loading,
        isUpdate,
        getTitle,
        buttons,
        dataModelId,
        getBoxWidth,
        init,
        registerDrawer,
        handleSubmit,
        registerForm,
        handleClose,
        handleBtnCustom,
      };
    },
  });
</script>
